package com.foreveross.crawl.common.jpa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.foreveross.crawl.common.cache.BufferInstance;
import com.foreveross.crawl.common.cache.Operations;
import com.foreveross.crawl.common.domain.IBaseEntity;

/**
 * @author tanzhixiong
 *
 */
/*@Repository("entityCacheHibernateRepository")*/
public class EntityCacheHibernateRepository extends EntityHibernateRepository 
	implements IBaseRepository{
	
	
	@Override
	public synchronized <T extends IBaseEntity> void save(List<T> instances) {
		//先排序
		List<BufferInstance> list = new ArrayList<BufferInstance>();
		for(IBaseEntity i : instances) {
			if(i instanceof BufferInstance){
				list.add((BufferInstance)i);
			}
		}
		Collections.sort(list);
		for(BufferInstance bi : list){
			if(bi.getOper().equals(Operations.CREATE)) {
				super.getHibernateTemplate().save(bi.getInstance());
			}else if(bi.getOper().equals(Operations.UPDATE)) {
				super.getHibernateTemplate().update(bi.getInstance());
			}else if(bi.getOper().equals(Operations.DELETE)) {
				super.getHibernateTemplate().delete(bi.getInstance());
			}
		}
	}

}
